package com.lml.hydrogenexpertsystem.backend.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author 梦龙
 * @date 2025/4/14 17:34
 */
@Service
public class VectorService {
    @Value("${vector.service.url}")
    private String vectorServiceUrl;

    private final RestTemplate restTemplate;

    public VectorService() {
        this.restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())
        );
        this.restTemplate.getInterceptors().add((request, body, execution) -> {
//            System.out.println("===> 实际请求地址: " + request.getURI());
            return execution.execute(request, body);
        });
    }

    public VectorService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public List<String> getContextDocuments(String question) {
        System.out.println("===> 正在请求向量服务，问题内容：" + question);
        System.out.println("===> 请求地址：" + vectorServiceUrl);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> request = Map.of("text", question);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        Map<String, Object> response;
        try {
            response = restTemplate.postForObject(vectorServiceUrl, entity, Map.class);
        } catch (HttpStatusCodeException e) {
            System.err.println("HTTP错误响应: " + e.getResponseBodyAsString());
            throw e;
        }
//        System.out.println("===> 向量服务响应：" + response);
        return (List<String>) response.get("documents");
    }
}
